<?php

namespace WxWorkSDK\Authorization;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

/**
 * Class Authorization
 * @package  WxWorkSDK\Authorization
 * @author   George
 * @datetime 2019/5/25 11:26
 * @annotation
 */
class Authorization
{
    /**
     * @var string
     * @annotation
     */
    private $corpId = "";
    /**
     * @var string
     * @annotation
     */
    private $secret = "";

    const URI = "gettoken";

    /**
     * Authorization constructor.
     * @param string $corpId
     * @param string $secret
     */
    public function __construct(string $corpId, string $secret)
    {
        $this->corpId = $corpId;
        $this->secret = $secret;
    }

    public function getToken()
    {
        if ($result = $this->check() !== TRUE) {
            return $result;
        }
        list($bool, $result) = Http::request('GET', self::URI, ['query' => [
            "corpid"     => $this->corpId,
            "corpsecret" => $this->secret
        ]]);
        if ($bool) {
            return $this->setResult($result);
        } else {
            return $result;
        }
    }

    /**
     * @return bool|Result
     * @annotation
     */
    private function check()
    {
        if (empty($this->corpId)) {
            return new Result(FALSE, Error::PARAM_MISTAKE, Error::NOT_CORP_ID_MSG);
        }
        if (empty($this->secret)) {
            return new Result(FALSE, Error::PARAM_MISTAKE, Error::NOT_SECRET_MSG);
        }
        return TRUE;
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function setResult($response): Result
    {
        $response = json_decode($response, TRUE);
        if ($response['errcode'] == 0) {
            return new Result(TRUE, 0, 'ok',
                              [
                                  'access_token' => $response['access_token'],
                                  'expires_in'   => $response['expires_in']
                              ]);
        } else {
            return new Result(FALSE, Error::WX_MISTAKE, $response['errcode'] . ':' . $response['errmsg']);
        }
    }
}